package com.googlecode.aleverr.yafotkiclient.ui.activities;

import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ViewSwitcher;
import com.googlecode.aleverr.yafotkiclient.R;
import com.googlecode.aleverr.yafotkiclient.api.Album;
import com.googlecode.aleverr.yafotkiclient.api.AlbumCollection;
import com.googlecode.aleverr.yafotkiclient.api.GlobalSettings;
import com.googlecode.aleverr.yafotkiclient.ui.adapters.AlbumsListAdapter;

public class AlbumsActivity extends ListActivity {

    private static final String TAG = "AlbumsActivity";

    private final AlbumsListAdapter albumsListAdapter = new AlbumsListAdapter();
    private String albumCollectionAddress;

    private static final int PROGRESS_BAR_INDEX = 0;
    private static final int LIST_VIEW_INDEX = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.albums);
        setListAdapter(albumsListAdapter);

        Intent intent = getIntent();
        albumCollectionAddress = intent.getStringExtra("albumCollectionAddress");

        new LoadAlbumsTask().execute();
    }

    private class LoadAlbumsTask extends AsyncTask<Void, Void, AlbumCollection> {

        @Override
        protected AlbumCollection doInBackground(Void... voids) {
            String accessToken = GlobalSettings.getInstance(AlbumsActivity.this).getAccessToken();
            return AlbumCollection.fromUrl(albumCollectionAddress, accessToken);
        }

        @Override
        protected void onPreExecute() {
            ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
            viewSwitcher.setDisplayedChild(PROGRESS_BAR_INDEX);
        }

        @Override
        protected void onPostExecute(AlbumCollection albumCollection) {
            Log.d(TAG, "LoadAlbumsTask: post execute");
            Log.d(TAG, "Entries: " + albumCollection.getEntries().size());
            albumsListAdapter.update(albumCollection.getEntries());

            ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
            viewSwitcher.setDisplayedChild(LIST_VIEW_INDEX);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Album album = albumsListAdapter.getItem(position);
        Log.d(TAG, "Clicked on: " + album.getTitle());

        Intent intent = new Intent(this, PhotoGridActivity.class);
        intent.putExtra("photoCollectionAddress", album.getPhotoCollectionAddress());
        intent.putExtra("albumId", album.getId());
        startActivity(intent);
    }
}